<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!-- 左侧部门树 -->
      <el-col :span="4" :xs="24">
        <div class="head-container">
          <el-input
            v-model="deptName"
            placeholder="请输入部门名称"
            clearable
            size="small"
            prefix-icon="el-icon-search"
            style="margin-bottom: 20px"
          />
        </div>
        <div class="head-container">
          <el-tree
            :data="deptOptions"
            :props="defaultProps"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            ref="tree"
            node-key="id"
            default-expand-all
            @node-click="handleNodeClick"
          />
        </div>
      </el-col>

      <!-- 右侧文档列表 -->
      <el-col :span="20" :xs="24">
        <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
          <el-form-item label="文档名称" prop="documentName">
            <el-input
              v-model="queryParams.documentName"
              placeholder="请输入文档名称"
              clearable
              size="small"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="文档分类" prop="documentType">
            <el-select v-model="queryParams.categoryId" placeholder="请选择文档分类" clearable size="small">
              <el-option
                v-for="dict in categoryOptions"
                :key="dict.categoryId"
                :label="dict.categoryName"
                :value="dict.categoryId"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-select v-model="queryParams.status" placeholder="请选择状态" clearable size="small">
              <el-option
                v-for="dict in statusOptions"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
              v-hasPermi="['system:document:add']"
            >新增</el-button>
          </el-col>
<!--          <el-col :span="1.5">
            <el-button
              type="success"
              plain
              icon="el-icon-edit"
              size="mini"
              :disabled="single"
              @click="handleUpdate"
              v-hasPermi="['system:document:edit']"
            >修改</el-button>
          </el-col>-->
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="el-icon-delete"
              size="mini"
              :disabled="multiple"
              @click="handleDelete"
              v-hasPermi="['system:document:remove']"
            >删除</el-button>
          </el-col>
<!--          <el-col :span="1.5">
            <el-button
              type="warning"
              plain
              icon="el-icon-download"
              size="mini"
              @click="handleExport"
              v-hasPermi="['system:document:export']"
            >导出</el-button>
          </el-col>-->
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="documentList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center" />
<!--          <el-table-column label="文档ID" align="center" prop="documentId" />-->
          <el-table-column label="文档名称" align="center" prop="documentName" :show-overflow-tooltip="true" />
          <el-table-column label="文档类型" align="center" prop="documentType">
            <template slot-scope="scope">
              <dict-tag :options="documentTypeOptions" :value="scope.row.documentType"/>
            </template>
          </el-table-column>
          <el-table-column label="文件大小" align="center" prop="fileSize">
            <template slot-scope="scope">
              {{ formatFileSize(scope.row.fileSize) }}
            </template>
          </el-table-column>
          <el-table-column label="所属部门" align="center" prop="deptName" />
          <el-table-column label="状态" align="center" prop="status">
            <template slot-scope="scope">
              <dict-tag :options="statusOptions" :value="scope.row.status"/>
            </template>
          </el-table-column>
          <el-table-column label="创建时间" align="center" prop="createTime" width="180">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.createTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-download"
                @click="handleDownload(scope.row)"
                v-hasPermi="['system:document:download']"
              >下载</el-button>
<!--              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['system:document:edit']"
              >修改</el-button>-->
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['system:document:remove']"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </el-col>
    </el-row>

    <!-- 添加或修改文档对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="文档名称" prop="documentName">
              <el-input v-model="form.documentName" placeholder="请输入文档名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属部门" prop="deptId">
              <treeselect v-model="form.deptId" :options="deptOptions" :show-count="true" placeholder="请选择所属部门" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
<!--            <el-form-item label="文档分类" prop="categoryId">
              <treeselect v-model="form.categoryId" :options="categoryOptions" :show-count="true" placeholder="请选择文档分类" />
            </el-form-item>-->
            <el-form-item label="文档分类" prop="categoryId">
              <treeselect
                v-model="form.categoryId"
                :options="categoryOptions"
                :normalizer="normalizer"
                placeholder="请选择文档分类"
                :clearable="true"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio
                  v-for="dict in statusOptions"
                  :key="dict.dictValue"
                  :label="dict.dictValue"
                >{{dict.dictLabel}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="文档描述" prop="documentDesc">
              <el-input v-model="form.documentDesc" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="上传文件" prop="file">
              <el-upload
                multiple
                ref="upload"
                :limit="1"
                name="file"
                accept=".doc,.docx,.xls,.xlsx,.ppt,.pptx,.pdf,.txt"
                :action="upload.url"
                :headers="upload.headers"
                :file-list="upload.fileList"
                :on-progress="handleFileUploadProgress"
                :on-success="handleFileSuccess"
                :on-change="handleFileChange"
                :auto-upload="false"
                drag
              >
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                <div class="el-upload__tip" slot="tip">支持扩展名：.doc .docx .xls .xlsx .ppt .pptx .pdf .txt</div>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listDocument,
  getDocument,
  delDocument,
  addDocument,
  updateDocument,
  exportDocument,
  listCategory,
  getDocumentCategoryTree
} from "@/api/system/document";
import {treeCurrentUser} from "@/api/system/dept";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { getToken } from "@/utils/auth";
import download from "@/plugins/download";

export default {
  name: "Document",
  components: { Treeselect },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 文档表格数据
      documentList: [],
      // 部门树选项
      deptOptions: [],
      // 文档分类树选项
      categoryOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 部门名称
      deptName: "",
      defaultDeptId: undefined,
      // 文档类型字典
      documentTypeOptions: [],
      // 状态字典
      statusOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        documentName: undefined,
        documentType: undefined,
        deptId: undefined,
        status: undefined,
        categoryId: undefined
      },
      // 表单参数
      form: {
        documentId: null,
        documentName: null,
        documentType: null,
        file: null,
        filePath: '',
        fileSize: 0,
        documentDesc: null,
        categoryId: null,
        deptId: null,
        status: "0",
        remark: null
      },
      // 表单校验
      rules: {
        documentName: [
          { required: true, message: "文档名称不能为空", trigger: "blur" }
        ],
        file: [
          { required: true, message: "请上传文件", trigger: "blur" }
        ],
        deptId: [
          { required: true, message: "所属部门不能为空", trigger: "blur" }
        ]
      },
      // 文件上传参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/system/document/upload",
        // 上传的文件列表
        fileList: []
      },
      defaultProps: {
        children: "children",
        label: "label"
      },
      normalizer(node) {
        return {
          id: node.categoryId,
          label: node.categoryName,
          children: node.children
        }
      }
    };
  },
  created() {
    this.getList();
    this.getTreeselect();
    //this.getCategoryTreeselect();
    this.getCategoryTree();
    this.getDicts("sys_document_type").then(response => {
      this.documentTypeOptions = response.data;
    });
    this.getDicts("sys_normal_disable").then(response => {
      this.statusOptions = response.data;
    });
  },
  watch: {
    // 根据部门名称筛选部门树
    deptName(val) {
      this.$refs.tree.filter(val);
    },

    deptOptions: {
      immediate: true,
      handler(newVal) {
        if (newVal && newVal.length > 0) {
          // 设置默认选中的第一个部门
          this.$nextTick(() => {
            // 获取第一个有效节点的ID
            const firstNodeId = this.findFirstNodeId(newVal);
            if (firstNodeId) {
              this.defaultDeptId = firstNodeId;
              this.queryParams.deptId = this.defaultDeptId;
              try {
                this.$refs.tree.setCurrentKey(this.defaultDeptId);
              } catch (e) {
                console.warn('设置树节点选中状态失败:', e);
              }
              this.getList();
            }
          });
        }
      }
    }
  },
  methods: {
    // 获取分类树数据
    async getCategoryTree() {
      try {
        getDocumentCategoryTree().then(response => {
          this.categoryOptions = this.buildTree(response.data)
        });
      } catch (error) {
        console.error('获取分类树失败:', error)
        this.$message.error('获取分类树失败')
      }
    },
    findFirstNodeId(nodes) {
      if (!nodes || nodes.length === 0) return null;
      const firstNode = nodes[0];
      if (firstNode.id) {
        return firstNode.id;
      }
      // 如果第一个节点有子节点，递归查找
      if (firstNode.children && firstNode.children.length > 0) {
        return this.findFirstNodeId(firstNode.children);
      }
      return null;
    },
    // 构建树形结构
    buildTree(data, parentId = 0) {
      const tree = []
      data
        .filter(item => item.parentId === parentId)
        .forEach(item => {
          const children = this.buildTree(data, item.categoryId)
          tree.push({
            ...item,
            children: children.length ? children : undefined
          })
        })
      return tree
    },
    /** 查询文档列表 */
    getList() {
      this.loading = true;
      listDocument(this.queryParams).then(response => {
        this.documentList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询部门下拉树结构 */
    getTreeselect() {
      treeCurrentUser().then(response => {
        this.deptOptions = response.data;
      });
    },
    /** 查询文档分类下拉树结构 */
    getCategoryTreeselect() {
      listCategory().then(response => {
        // 转换类型
        const processedData = response.data.map(item => ({
          ...item,
          parentId: Number(item.parentId)
        }))
        this.categoryOptions = this.handleTree(processedData, "categoryId", "parentId")
      });
    },

    // 更健壮的树形数据处理
    buildCategoryTree(data, options = {}) {
      const {
        idKey = 'id',
        parentKey = 'parentId',
        childrenKey = 'children',
        rootParentId = 0
      } = options

      // 1. 数据校验
      if (!Array.isArray(data)) {
        console.error('[buildTree] 数据必须为数组')
        return []
      }

      // 2. 创建映射表
      const nodeMap = new Map()
      data.forEach(item => {
        const node = { ...item }
        node[childrenKey] = []
        nodeMap.set(node[idKey], node)
      })

      // 3. 构建树
      const tree = []
      nodeMap.forEach(node => {
        const parentId = node[parentKey] !== undefined ? node[parentKey] : rootParentId
        if (parentId === rootParentId || !nodeMap.has(parentId)) {
          tree.push(node)
        } else {
          const parent = nodeMap.get(parentId)
          if (parent) {
            if (!parent[childrenKey]) {
              parent[childrenKey] = []
            }
            parent[childrenKey].push(node)
          }
        }
      })

      // 4. 按指定字段排序（可选）
      const sortTree = (nodes, sortKey) => {
        if (!sortKey) return nodes
        return nodes.sort((a, b) => {
          const valA = a[sortKey] || 0
          const valB = b[sortKey] || 0
          return valA - valB
        }).map(node => ({
          ...node,
          [childrenKey]: node[childrenKey] ? sortTree(node[childrenKey], sortKey) : []
        }))
      }

      return sortTree(tree, options.sortKey)
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.deptId = data.id;
      this.getList();
    },
    // 文件大小格式化
    formatFileSize(size) {
      if (!size) return "0 B";
      const unitArr = ["B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"];
      const index = Math.floor(Math.log(size) / Math.log(1024));
      const formattedSize = (size / Math.pow(1024, index)).toFixed(2);
      return formattedSize + " " + unitArr[index];
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        documentId: null,
        documentName: null,
        documentType: null,
        file: null,
        filePath: '',
        fileSize: 0,
        documentDesc: null,
        categoryId: null,
        deptId: null,
        status: "0",
        remark: null
      };
      this.upload.fileList = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams.deptId = undefined;
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.documentId);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加文档";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const documentId = row.documentId || this.ids;
      getDocument(documentId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改文档";
        this.upload.fileList = [{ name: this.form.documentName }];
      });
    },

    handleFileChange(file, fileList) {
      // 确保只保留一个文件（因为limit=1）
      if (fileList.length > 1) {
        this.upload.fileList = [fileList[fileList.length - 1]];
      }

      // 将原始文件对象保存到form中
      this.form.file = fileList.length > 0 ? fileList[0].raw : null;

      // 手动验证文件字段
      this.$refs.form.validateField('file');
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 再次确认文件存在
          if (!this.form.file) {
            this.$message.error('请上传文件');
            return;
          }
          this.$refs.upload.submit();
        }
      });
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.isUploading = false;
      // 将原始文件对象保存到form中
      /*this.form.file = file.raw;*/
      const formData = new FormData();
      //formData.append('file', file.raw); // 关键：字段名必须与后端一致
      //formData.append('file', file.raw, file.name);
      formData.append('filePath', response.url);
      formData.append('fileSize', file.size);
      formData.append('documentType', file.name.substring(file.name.lastIndexOf(".") + 1));
      // 3. 添加其他表单数据
      formData.append('documentName', this.form.documentName);
      formData.append('deptId', this.form.deptId);
      formData.append('categoryId', this.form.categoryId);
      formData.append('status', this.form.status);
      formData.append('documentDesc', this.form.documentDesc);

      if (this.form.documentId != null) {
        updateDocument(formData).then(response => {
          this.$modal.msgSuccess("修改成功");
          this.open = false;
          this.getList();
        });
      } else {
        addDocument(formData).then(response => {
          this.$modal.msgSuccess("新增成功");
          this.open = false;
          this.getList();
        });
      }
    },
    /** 下载按钮操作 */
    handleDownload(row) {
      download.downloadDocument(row.documentId);
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      if(row.categoryId == 2){
        this.$modal.msg('流程文档不可删除！');
        return;
      }
      const documentIds = row.documentId || this.ids;
      this.$modal.confirm('是否确认删除文档编号为"' + documentIds + '"的数据项？').then(function() {
        return delDocument(documentIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$modal.confirm('是否确认导出所有文档数据项？').then(() => {
        this.exportLoading = true;
        return exportDocument(queryParams);
      }).then(response => {
        this.$download.name(response.msg);
        this.exportLoading = false;
      }).catch(() => {});
    },
    blobValidate(data) {
      return data.type !== 'application/json'
    }
  }
};
</script>

<style scoped>
/* 调整树形结构样式 */
.el-tree {
  min-height: 400px;
  overflow-y: auto;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 10px;
}

/* 调整上传组件样式 */
.el-upload {
  width: 100%;
}

.el-upload-dragger {
  width: 100%;
  height: 180px;
}
</style>
